package com.codeczx.mymultidownloaddemo;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

public class DownloadService extends Service {

    private static final String TAG = "DownloadService";
    public static final String DOWNLOAD_URL = "url";
    private HashMap<String, Disposable> disposables;
    private int count = 0;
    private Map<String, Integer> downloadItems;

    public DownloadService() {
        disposables = new HashMap<>();
        downloadItems = new HashMap<>();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String url = intent.getExtras().getString(DOWNLOAD_URL);
        Log.i(TAG, "onStartCommand: " + url);
        new Thread(new DownloadRunnable(url)).start();
        return START_NOT_STICKY;
    }

    class DownloadRunnable implements Runnable {

        private String url;
        private int lastPercent = 0;

        DownloadRunnable(String url) {
            this.url = url;
        }

        @Override
        public void run() {
            String folderPath = DownloadService.this.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
            final String fileName = url.substring(url.lastIndexOf("/") + 1);
            Log.i(TAG, "run: filename:" + fileName);
            final Disposable disposable = RxDownload.getInstance(DownloadService.this)
                    .download(url, fileName, folderPath)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<DownloadStatus>() {
                        @Override
                        public void accept(@NonNull DownloadStatus downloadStatus) throws Exception {
                            int percent = (int) Float.parseFloat(downloadStatus.getPercent().replace("%", ""));
                            if (percent > lastPercent) {
//                                Log.i(TAG, "accept: "+fileName+" "+downloadStatus.getPercent());
                                getNotificationManager().notify(downloadItems.get(url), getNotification(fileName, percent));
                                lastPercent = percent;
                            }
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(@NonNull Throwable throwable) throws Exception {
                            throwable.printStackTrace();
                        }
                    }, new Action() {
                        @Override
                        public void run() throws Exception {
                            Log.i(TAG, "run: success");

                            disposables.remove(url);
                        }
                    });
            disposables.put(url, disposable);
            synchronized (DownloadService.class) {
                downloadItems.put(url, count);
                DownloadService.this.startForeground(count, getNotification(fileName, 0));
                count++;
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private NotificationManager getNotificationManager() {
        return (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    private Notification getNotification(String title, int progress) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(title);
        builder.setSmallIcon(R.mipmap.ic_launcher);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));
        if (progress > 0) {
            builder.setContentText(progress + "%");
            builder.setProgress(100, progress, false);
        }
        return builder.build();
    }
}
